import ScrollPageList, { PageListRef } from '@/components/ScrollPageList';
import { audioSynthesisV1ControllerIndexEarbuds2Earbuds } from '@/services/auto/audioSynthesis';
import { ProTable } from '@ant-design/pro-components';
import { css } from '@emotion/react';
import { Link } from '@umijs/max';
import { Button } from 'antd';
import { GetScrollPageParam } from 'common/interface';
import { SimulationAlgoType, simulationAlgoType } from 'common/utils/data';
import { getFilenameByKey } from 'common/utils/utils';
import { Fragment, useEffect, useRef, useState } from 'react';
import Add from './Add';
import Status from './Status';

export default ({ onAdd }: { onAdd: () => void }) => {
  const [searchParam, setSearchParam] = useState<{ keyword?: string }>();

  const scrollPageListRef =
    useRef<PageListRef<API.AudioSynthesisIndexEarbuds2EarbudsResult>>(null);

  const [list, setList] =
    useState<API.AudioSynthesisIndexEarbuds2EarbudsResult[]>();

  const [count, setCount] = useState<number>();

  const [loading, setLoading] = useState<boolean>();

  const [showPageScroll, setShowPageScroll] = useState<boolean>(false);

  useEffect(() => {
    setShowPageScroll(true);
  }, []);

  const elementRef = useRef<HTMLDivElement>(null);

  return (
    <div
      ref={elementRef}
      className="h-full"
      css={css`
        .ant-pro-table,
        .ant-pro-card,
        .ant-pro-card-body {
          height: 100% !important;
        }

        .ant-table-wrapper {
          height: calc(100% - 64px);

          .ant-spin-nested-loading,
          .ant-spin-container,
          .ant-table,
          .ant-table-container {
            height: 100%;
          }

          .ant-table-body {
            height: calc(100% - 47px);
          }
        }
      `}
    >
      <ProTable<API.AudioSynthesisIndexEarbuds2EarbudsResult>
        loading={loading}
        rowKey="uuid"
        scroll={{ y: '100%', scrollToFirstRowOnChange: true }}
        search={false}
        dataSource={list}
        pagination={false}
        toolbar={{
          settings: [],
          search: {
            onSearch: (value: string) => {
              setSearchParam({ keyword: value || undefined });
              scrollPageListRef.current?.scrollToTop();
            },
          },
          actions: [
            <span key="count">共计 {count ?? '-'} 条</span>,
            <Add
              key="add"
              reload={() => {
                onAdd();
                scrollPageListRef.current?.refresh();
              }}
            >
              <Button type="primary">添加云试听任务</Button>
            </Add>,
          ],
        }}
        columns={[
          {
            title: '序号',
            key: 'index',
            width: 80,
            valueType: 'index',
          },
          {
            title: '生成耳机',
            dataIndex: 'targetName',
            render: (_, record) => {
              return (
                <Fragment>
                  {record.targetName}
                  {record.audioSynthesisEarbuds2earbuds
                    ?.targetEvaluationUuid && (
                    <Fragment>
                      <Link
                        className="ml-[8px]"
                        to={{
                          pathname: `/evaluation/${record.audioSynthesisEarbuds2earbuds.targetEvaluationUuid}`,
                        }}
                        target="_blank"
                      >
                        实测数据
                      </Link>
                      {record.audioSynthesisEarbuds2earbuds.targetEvaluation
                        .buyUrl && (
                        <a
                          className="ml-[8px]"
                          href={
                            record.audioSynthesisEarbuds2earbuds
                              .targetEvaluation.buyUrl
                          }
                          target="_blank"
                        >
                          电商详情
                        </a>
                      )}
                    </Fragment>
                  )}
                </Fragment>
              );
            },
          },
          {
            title: '源耳机',
            dataIndex: 'currentName',
            render: (_, record) => {
              return (
                <Fragment>
                  {record.currentName}
                  {record.audioSynthesisEarbuds2earbuds
                    ?.currentEvaluationUuid && (
                    <Fragment>
                      <Link
                        className="ml-[8px]"
                        to={{
                          pathname: `/evaluation/${record.audioSynthesisEarbuds2earbuds.currentEvaluationUuid}`,
                        }}
                        target="_blank"
                      >
                        实测数据
                      </Link>
                      {record.audioSynthesisEarbuds2earbuds.currentEvaluation
                        .buyUrl && (
                        <a
                          className="ml-[8px]"
                          href={
                            record.audioSynthesisEarbuds2earbuds
                              .currentEvaluation.buyUrl
                          }
                          target="_blank"
                        >
                          电商详情
                        </a>
                      )}
                    </Fragment>
                  )}
                </Fragment>
              );
            },
          },
          {
            title: '源音频文件',
            dataIndex: 'currentAudioFile',
            render: (_, record) => {
              return getFilenameByKey(record.currentAudioFile);
            },
          },
          {
            title: '模拟算法',
            dataIndex: ['audioSynthesisEarbuds2earbuds', 'simulationAlgo'],
            width: 200,
            render: (val) => {
              return val
                ? simulationAlgoType[val as SimulationAlgoType]
                : simulationAlgoType[SimulationAlgoType.TONING];
            },
          },
          {
            title: '状态',
            dataIndex: 'status',
            width: 200,
            render: (_, record) => {
              return <Status data={record} />;
            },
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'dateTime',
            width: 150,
          },
        ]}
      />
      {showPageScroll && (
        <ScrollPageList<
          GetScrollPageParam<API.AudioSynthesisV1ControllerIndexEarbuds2EarbudsParams>,
          API.AudioSynthesisIndexEarbuds2EarbudsResult
        >
          ref={scrollPageListRef}
          param={searchParam}
          service={audioSynthesisV1ControllerIndexEarbuds2Earbuds}
          order={{
            orderBy: 'createTime',
            direction: 'DESC',
          }}
          getScrollableTarget={() =>
            elementRef.current?.querySelector('.ant-table-body')!
          }
          onListChange={(l, c) => {
            setList(l);
            setCount(c);
          }}
          onLoadingChange={(l) => {
            setLoading(l);
          }}
        />
      )}
    </div>
  );
};
